package com.lanbu.chat.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.lanbu.chat.domain.dto.FastGptResponse;
import com.lanbu.chat.service.IImFastGptService;
import com.lanbu.common.config.KnowledgeProperties;
import com.lanbu.common.constant.DeptConstants;
import com.lanbu.common.core.controller.BaseController;
import com.lanbu.common.core.domain.AjaxResult;
import com.lanbu.common.core.domain.entity.SysDept;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.core.domain.vo.FastGptOpenapiVo;
import com.lanbu.common.core.page.TableDataInfo;
import com.lanbu.common.utils.SecurityUtils;
import com.lanbu.system.domain.mongo.MongoOutlinks;
import com.lanbu.system.service.ISysDeptService;
import com.lanbu.system.service.impl.MongoOutlinksService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/fastGpt/manager")
@RequiredArgsConstructor
public class ImFastGptController extends BaseController
{
    private final RestTemplate restTemplate;
    @Value("${gptLoginUrl}")
    private  String gptLoginUrl ;

    private  String gptRequestBody = "{\"username\":\"%s\",\"password\":\"%s\"}";
    @Value("${domain}")
    private  String domain ;
    @Value("${gptUrl}")
    private  String gptUrl;
  @Autowired
   private final MongoOutlinksService mongoOutlinksService;

    private final KnowledgeProperties knowledgeProperties;

    private final IImFastGptService iImFastGptService;

    private final ISysDeptService deptService;

    @GetMapping("/toFastGpt")
    @ResponseBody
    public AjaxResult toFastGpt(HttpServletRequest request, HttpServletResponse servletResponse) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        SysDept dept = user.getDept();
        String ancestors = dept.getAncestors();
        // 如果登录的用户部门不是第一层级，则向上找到第一层级
        List<String> splitByAncestors = StrUtil.split(ancestors, ",");
        if(splitByAncestors.size() > DeptConstants.DEPT_UNION_FAST_GPT_DEEP){
            String s = splitByAncestors.get(DeptConstants.DEPT_UNION_FAST_GPT_DEEP);
            dept = deptService.selectDeptById(Long.valueOf(s));
        }

        String url = gptLoginUrl;
        //不是admin，则使用,组织id+ILOVEYOU ,登录
        String jsonBody = String.format(gptRequestBody,dept.getDeptId()+ DeptConstants.DEPT_UNIQUE_SUFFIX_STR, SecureUtil.sha256(dept.getDeptId()+ DeptConstants.DEPT_UNIQUE_SUFFIX_STR));

        // 如果是 admin 则用 root 1234 登录
        if(user.isAdmin()){
            jsonBody = String.format(gptRequestBody, knowledgeProperties.getRootName(), SecureUtil.sha256(knowledgeProperties.getRootPwd()));
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);


        HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
        //使用账户密码登录
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        String body = response.getBody();
        FastGptResponse bean = JSONUtil.toBean(body, FastGptResponse.class);
        String token = bean.getData().getToken();

        //设置Cookie
        Cookie cookie = new Cookie("fastgpt_token", token);
        cookie.setPath("/");
        cookie.setMaxAge(12 * 60 * 60);
        cookie.setHttpOnly(true);
        cookie.setDomain(domain);
//        cookie.setSecure(true);
//        cookie.setComment("SameSite=None");
        servletResponse.addCookie(cookie);
        return success().put("url",gptUrl);
    }

    @ApiOperation("查询 fastGpt openapi")
    @GetMapping("/openapiList")
    public TableDataInfo openapiList()
    {
        // todo 分页
        startPage();
        List<FastGptOpenapiVo> fastGptOpenapiVos = iImFastGptService.selectOpenapiList();
        return getDataTable(fastGptOpenapiVos);
    }


    @ApiOperation("查询 fastGpt shareid")
    @GetMapping("/shareidList")
    public TableDataInfo shareid()
    {
        // todo 分页
        startPage();
        List<MongoOutlinks> fastGptShareidVos = mongoOutlinksService.findAll();
        return getDataTable(fastGptShareidVos);
    }
}
